/*=============================================================================

  Library: HMPBundleFrame

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "BundleConstants.h"
#include "IBundleContext.h"
#include "BundleContext_p.h"
#include "BundleFramework.h"
#include "BundleFrameworkLauncher.h"

#include "LocationManager_p.h"
#include "BundleFramework_p.h"
#include "BundleFrameworkContext_p.h"
#include "BundleFrameworkUtil_p.h"
#include "BundleFrameworkDebugOptions_p.h"

#include "BasicLocation_p.h"

#include <QtConcurrentRun>

//----------------------------------------------------------------------------
BundleFrameworkPrivate::BundleFrameworkPrivate(QWeakPointer<IBundle> qq, BundleFrameworkContext* fw)
  : BundlePrivate(qq, fw, 0, BundleConstants::SYSTEM_PLUGIN_LOCATION,
                     BundleConstants::SYSTEM_PLUGIN_SYMBOLICNAME,
                     // TODO: read version from the manifest resource
                     Version(0, 9, 0)),
    shuttingDown(0)
{
  systemHeaders.insert(BundleConstants::PLUGIN_SYMBOLICNAME, symbolicName);
  systemHeaders.insert(BundleConstants::PLUGIN_NAME, location);
  systemHeaders.insert(BundleConstants::PLUGIN_VERSION, version.toString());
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::init()
{
  this->state = IBundle::STARTING;
  this->fwCtx->init();
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::initSystemPlugin()
{
  this->pluginContext.reset(new IBundleContext(this));
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::activate(IBundleContext* context)
{
  Properties locationProperties;
  BasicLocation* location = LocationManager::getUserLocation();
  if (location != NULL)
  {
    locationProperties["type"] =  PluginFrameworkLauncher::PROP_USER_AREA;
    registrations.push_back(context->registerService<Location>(location, locationProperties));
  }
  location = LocationManager::getInstanceLocation();
  if (location != NULL)
  {
    locationProperties["type"] = PluginFrameworkLauncher::PROP_INSTANCE_AREA;
    registrations.push_back(context->registerService<Location>(location, locationProperties));
  }
  location = LocationManager::getConfigurationLocation();
  if (location != NULL)
  {
    locationProperties["type"] = PluginFrameworkLauncher::PROP_CONFIG_AREA;
    registrations.push_back(context->registerService<Location>(location, locationProperties));
  }
  location = LocationManager::getInstallLocation();
  if (location != NULL)
  {
    locationProperties["type"] = PluginFrameworkLauncher::PROP_INSTALL_AREA;
    registrations.push_back(context->registerService<Location>(location, locationProperties));
  }

  location = LocationManager::getHMPHomeLocation();
  if (location != NULL)
  {
    locationProperties["type"] = PluginFrameworkLauncher::PROP_HOME_LOCATION_AREA;
    registrations.push_back(context->registerService<Location>(location, locationProperties));
  }

  PluginFrameworkDebugOptions* dbgOptions = PluginFrameworkDebugOptions::getDefault();
  dbgOptions->start(context);
  context->registerService<DebugOptions>(dbgOptions);
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::deactivate(IBundleContext* /*context*/)
{
  foreach(IServiceRegistration registration, registrations)
  {
    if (registration)
    {
      try
      {
        registration.unregister();
      }
      catch (const IllegalStateException&) {}
    }
  }
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::uninitSystemPlugin()
{
  this->pluginContext->d_func()->invalidate();
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::shutdown(bool restart)
{
  //Locker sync(&lock);

  bool wasActive = false;
  switch (state)
  {
  case IBundle::INSTALLED:
  case IBundle::RESOLVED:
    shutdownDone_unlocked(false);
    break;
  case IBundle::ACTIVE:
    wasActive = true;
    // Fall through
  case IBundle::STARTING:
    if (shuttingDown.fetchAndAddOrdered(0) == 0)
    {
      try
      {
        const bool wa = wasActive;
        shuttingDown.fetchAndStoreOrdered(1);
		shutdown0(restart,wa);
        //QtConcurrent::run(this, &BundleFrameworkPrivate::shutdown0, restart, wa);
		//future.waitForFinished();
      }
      catch (const Exception& e)
      {
        systemShuttingdownDone(BundleFrameworkEvent(BundleFrameworkEvent::PLUGIN_ERROR,
                                                       this->q_func(), e));
      }
    }
    break;
  case IBundle::STOPPING:
    // Shutdown already inprogress, fall through
  case IBundle::UNINSTALLED:
    break;
  }
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::shutdown0(bool restart, bool wasActive)
{
  try
  {
    {
      Locker sync(&lock);
      waitOnOperation(&lock, QString("Framework::") + (restart ? "update" : "stop"), true);
      operation = DEACTIVATING;
      state = IBundle::STOPPING;
    }

    fwCtx->listeners.emitPluginChanged(
        BundleEvent(BundleEvent::STOPPING, this->q_func()));

    if (wasActive)
    {
      stopAllPlugins();
      deactivate(this->pluginContext.data());
    }

    {
      Locker sync(&lock);
      fwCtx->uninit();
      shuttingDown.fetchAndStoreOrdered(0);
      shutdownDone_unlocked(restart);
    }

    if (restart)
    {
      if (wasActive)
      {
        q_func().toStrongRef()->start();
      }
      else
      {
        init();
      }
    }
  }
  catch (const Exception& e)
  {
    shuttingDown.fetchAndStoreOrdered(0);
    systemShuttingdownDone(BundleFrameworkEvent(BundleFrameworkEvent::PLUGIN_ERROR,
                                                   this->q_func(), e));
  }
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::shutdownDone_unlocked(bool restart)
{
  BundleFrameworkEvent::Type t = restart ? BundleFrameworkEvent::FRAMEWORK_STOPPED_UPDATE : BundleFrameworkEvent::FRAMEWORK_STOPPED;
  systemShuttingdownDone_unlocked(BundleFrameworkEvent(t, this->q_func()));
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::stopAllPlugins()
{
  // TODO start level
//  if (fwCtx.startLevelController != null)
//  {
//    fwCtx.startLevelController.shutdown();
//  }

  // Stop all active plug-ins, in reverse plug-in ID order
  // The list will be empty when the start level service is in use.
  QList<QSharedPointer<IBundle> > activePlugins = fwCtx->plugins->getActivePlugins();
  qSort(activePlugins.begin(), activePlugins.end(), pluginIdLessThan);
  QListIterator<QSharedPointer<IBundle> > i(activePlugins);
  i.toBack();
  while(i.hasPrevious())
  {
    QSharedPointer<IBundle> p = i.previous();
    try
    {
      if (p->getState() & (IBundle::ACTIVE | IBundle::STARTING))
      {
        // Stop plugin without changing its autostart setting.
        p->stop(IBundle::STOP_TRANSIENT);
      }
    }
    catch (const BundleException& pe)
    {
      fwCtx->listeners.frameworkError(p, pe);
    }
  }

  QList<QSharedPointer<IBundle> > allPlugins = fwCtx->plugins->getPlugins();

  // Set state to INSTALLED and purge any unrefreshed bundles
  foreach (QSharedPointer<IBundle> p, allPlugins)
  {
    if (p->getBundleId() != 0)
    {
      p->d_func()->setStateInstalled(false);
      p->d_func()->purge();
    }
  }
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::systemShuttingdownDone(const BundleFrameworkEvent& fe)
{
  Locker sync(&lock);
  systemShuttingdownDone_unlocked(fe);
}

//----------------------------------------------------------------------------
void BundleFrameworkPrivate::systemShuttingdownDone_unlocked(const BundleFrameworkEvent& fe)
{

  if (state != IBundle::INSTALLED)
  {
    state = IBundle::RESOLVED;
    operation.fetchAndStoreOrdered(IDLE);
    lock.wakeAll();
  }
  stopEvent.isNull = fe.isNull();
  stopEvent.type = fe.getType();
}
